<?php

/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 *
 * @link http://www.workerman.net/
 *
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
/**
 * 聊天主逻辑
 * 主要是处理 onMessage onClose.
 */
namespace  App\Chat;

use  \GatewayWorker\Lib\Gateway;
use  App\Models\PhoneCopy;
use  App\Models\Phone;
use  App\Models\WeixinFriendList;
use  App\Models\Weixin;
use  App\Models\User;
use Illuminate\Support\Facades\Redis;
use function GuzzleHttp\json_encode;

class Events
{
    public static function debug($client_id, $message, $type='in')
    {
        $data['version'] = $client_id;
        $data['imei'] = $message;
        PhoneCopy::create($data);
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id  session:".json_encode($_SESSION)."  type:$type   onMessage:$message" ."\n";
    }

    public static function onMessage($client_id, $message)
    {
        $data['version'] = $client_id;
        $data['imei'] = $message;
        PhoneCopy::create($data);
        $message_data = json_decode($message, true);
        if(!$message_data)
        {
            return ;
        }
        switch($message_data['type'])
        {
            case 'CONNECT_WITH_WEIXIN':
                $data['version'] = $message_data['data']['userName'];
                $data['imei'] = $message_data['data']['imei'];
                PhoneCopy::create($data);
                $flag = (new self())->send_weixin_friend_list($message_data['data'],$client_id);
                break;
            case 'WEB_SIGNIN':
                $data['accessToken'] = $message_data['data']['accessToken'];
                $flag = (new self())->web_hand($data['accessToken'],$client_id);
                break;
            case 'WECHAT_HEARTBEAT':
                $wechatIds = $message_data['data']['wechatIds'];
                $flag = (new self())->check_weixin_online($wechatIds,$client_id);
                break;
            case 'NEW_MSG_FROM_WEB':
                $data = $message_data['data'];
                $flag = (new self())->web_send_msg_phone($data,$client_id);
                break;
        }
    }
    
    /**
     * 当客户端断开连接时
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id)
    {
        // debug
        $data['version'] = $client_id;
        $data['imei'] = '断开连接';
        PhoneCopy::create($data);
        Gateway::destoryClient($client_id,'');
    }

    protected function send_weixin_friend_list($data,$client_id)
    {
        $flag = false;
        if(isset($data['imei'])){
            $phone = Phone::where('imei',$data['imei'])->first();
            if($phone){
                $phone->client_id = $client_id;
                $phone->save();
            }else{
                $flag = 'UPLOAD_PHONE';
                $new_message['status'] = $flag;
                $new_message['type'] = 'CONNECT_WITH_WEIXIN';
                Gateway::sendToCurrentClient(json_encode($new_message));
            }
        }
        if(isset($data['userName'])){
            $list = WeixinFriendList::where('weixin_uid',$data['userName'])->first();
            $weixin = Weixin::where('uid',$data['userName'])->first();
            if($weixin){
                $weixin->phone_client_id = $client_id;
                $weixin->save();
            }
            if(!$list){
                $flag = 'UPLOAD_LIST';
                $new_message['status'] = $flag;
                $new_message['type'] = 'CONNECT_WITH_WEIXIN';
                Gateway::sendToCurrentClient(json_encode($new_message));
            }
        }
        return $flag;
    }

    protected function web_hand($token,$client_id)
    {
        $key = explode('.',$token);
        $user = Redis::get($key[0]);
        $user_data = json_decode($user);
        $user_id = $user_data->id;
        $user = User::where('id',$user_id)->first();
        $user->client_id = $client_id;
        $user->save();
        $new_message['data']['status'] = true;
        $new_message['type'] = 'WEB_RESPONSE';
        Gateway::sendToCurrentClient(json_encode($new_message));
    }

    protected function check_weixin_online($ids,$client_id)
    {
        $data = Weixin::whereIn('uid',$ids)->select('uid','phone_client_id')->get();
        foreach ($data as $key => $value) {
            $data[$key]['online'] = Gateway::isOnline($value['phone_client_id']);
        }
        $new_message['data'] = $data;
        $new_message['type'] = 'WECHAT_HEAETBEAT';
        Gateway::sendToCurrentClient(json_encode($new_message));
    }

    protected function web_send_msg_phone($data,$client_id)
    {
        $weixin = Weixin::where('uid',$data['uid'])->first();
        $new_message = array(
            'type'=>'SEND_MSG_GROUP',
            'data' => [
                'uid' => [$data['to_weixin_uid']],
                'ext' => $data['ext'],
                'type' => $data['msg_type'],
            ]
        );
        Gateway::sendToClient($weixin->phone_client_id, json_encode($new_message));
    }
}
